package com.xzcs.service.sysmgr;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzcs.mapper.attachment.AttachmentMapper;
import com.xzcs.service.BaseService;
import com.xzcs.util.Constants;
import com.xzcs.util.common.DateUtils;
import com.xzcs.util.common.FileUtils;
import com.xzcs.util.common.IpUtils;
import com.xzcs.util.common.StringUtils;
import com.xzcs.util.web.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class FileMgrService extends BaseService {
	
	@Autowired
	private AttachmentMapper attachmentMapper;

	public Map<String, Object> uploadFile(MultipartHttpServletRequest request) {
		String dir = RequestUtils.getMpValue(request, "dir").replaceAll("／", "/");
		String moduleName = RequestUtils.getMpValue(request, "moduleName");
		String downloadType = RequestUtils.getMpValue(request, "downloadType");
		downloadType = downloadType.equals("") ? "1" : downloadType;//默认通过下载引擎
		String remark = RequestUtils.getMpValue(request, "remark");
		List<MultipartFile> files = request.getFiles("files");
		String fileRoot = propertyUtils.getPropertyValue(Constants.DEFAULT_FILE_UPLOAD_PATH);
		Map<String, Object> user = this.getUser(request);
		Map<String, Object> result = new HashMap<String, Object>();
		for (MultipartFile file : files) {
			if (file.isEmpty()) {
				result.put("result", -1);
				result.put("msg", "请选择文件!");
				return result;
			}
			String fileName = file.getOriginalFilename();    // 原始文件名
			String attachmentSuffix = "";
			if (fileName.lastIndexOf(".") != -1) {
				attachmentSuffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			}
			String filePath = "";
			if (attachmentSuffix.equals("gif") || attachmentSuffix.equals("jpg")
					|| attachmentSuffix.equals("jpeg") || attachmentSuffix.equals("bmp")
					|| attachmentSuffix.equals("png")) {//图片
				filePath = "images/" + DateUtils.getToday("yyyyMMdd") + "/" + dir;
			} else {
				filePath = "files/" + DateUtils.getToday("yyyyMMdd") + "/" + dir;
			}

			long attachmentSize = file.getSize();// 文件大小
			String attachmentId = UUID.randomUUID().toString(); //附件编号
			String newFileName = attachmentId + "." + attachmentSuffix;//新文件名
			File saveDir = new File(fileRoot + filePath);
			// 如果目录不存在，创建目录
			if (!saveDir.exists() && !saveDir.isDirectory()) {
				saveDir.mkdirs();
			}

			// 将文件复制到指定目录中
			int exc = FileUtils.copyFile(file, fileRoot + filePath + newFileName);
			if (exc == 1) { //复制文件成功
				Map<String, Object> attachment = new HashMap<String, Object>();
				attachment.put("attachmentId", attachmentId);
				attachment.put("attachmentPath", filePath + newFileName);
				attachment.put("attachmentSize", attachmentSize);
				attachment.put("attachmentSuffix", attachmentSuffix);
				attachment.put("fileName", fileName);
				attachment.put("fileRoot", fileRoot);
				attachment.put("uploadIp", IpUtils.getClientIP(request));
				if (null != user) {
					attachment.put("uploadUser", StringUtils.get(user, "user_id"));
				}
				attachment.put("moduleName", moduleName);
				attachment.put("remark", remark);
				attachment.put("downloadType", downloadType);
				attachmentMapper.insertAttachment(attachment);
				result.put("result", 1);
				result.put("msg", "上传成功!");
				result.put("attachmentId", attachmentId);
				result.put("fileName", fileName);
				result.put("downloadType", downloadType);
				result.put("filePath", "/" + filePath + newFileName);
				return result;
			} else {//复制文件失败
				result.put("result", 0);
				result.put("msg", "上传失败!");
				result.put("fileName", fileName);
				return result;
			}
		}
		return result;
	}
	
	public int downloadFile(HttpServletRequest request, HttpServletResponse response) {
		String attachmentId = RequestUtils.getValue(request, "attachmentId");
        Map<String, Object> attachment = attachmentMapper.findAttachment(attachmentId);
        
        String attachmentPath = StringUtils.get(attachment, "attachment_path");
        String fileName = StringUtils.get(attachment, "file_name");
        String fileRoot = propertyUtils.getPropertyValue(Constants.DEFAULT_FILE_UPLOAD_PATH);
        File file = new File(fileRoot + attachmentPath);
        if(!file.exists()) {
            return -1; // 文件不存在
        }
        
        FileInputStream fis = null;
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
        	String newFileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", " ");
            response.reset();
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment;filename=" + newFileName);
            response.setContentLength((int)file.length());
            
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[1024];
            int bytesRead;
            while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception ex) {
            return -2;  // 文件读写异常
        } finally {
            try {
                bos.close();
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
                return -2; 
            }
        }
        
        return 1;
	}
	
	public PageInfo<Map<String, Object>> findAttachments(HttpServletRequest request){
		String pageNum = RequestUtils.getValue(request, "page");//页数
		String pageSize = RequestUtils.getValue(request, "rows");//每页条数
		pageNum = pageNum.equals("") ? "1" : pageNum;
		pageSize = pageSize.equals("") ? getDefaultPageSize() : pageSize;
		Map<String, Object> params = RequestUtils.getRequestMap(request);
		String startTime = RequestUtils.getValue(request, "startTime");
		String endTime = RequestUtils.getValue(request, "endTime");
		startTime = startTime.equals("") ? DateUtils.getDay(-7, "yyyy-MM-dd") : startTime;
		endTime = endTime.equals("") ? DateUtils.getToday("yyyy-MM-dd") : endTime;
		params.put("startTime", startTime);
		params.put("endTime", endTime);
		
		PageHelper.startPage(StringUtils.toInt(pageNum), StringUtils.toInt(pageSize));
		List<Map<String, Object>> list = attachmentMapper.findAttachments(params);
		PageInfo<Map<String, Object>> page = new PageInfo<Map<String, Object>>(list);
		return page;
	}

	public void deleteFile(HttpServletRequest request) {
		String attachmentId = RequestUtils.getValue(request, "attachmentId");
		Map<String, Object> attachment = attachmentMapper.findAttachment(attachmentId);
		String attachmentPath = StringUtils.get(attachment, "attachment_path");
		String fileRoot = StringUtils.get(attachment, "file_root");
		File file = new File(fileRoot + attachmentPath);
		if(file.exists()) {
			file.delete();
		}
		attachmentMapper.deleteAttachment(attachmentId);
	}
}
